package controllers

import (
	"strconv"

	"github.com/gin-gonic/gin"
	medical_dept_dao "jjqzplucky.site/sz-core/internal/dao/medical_dept"
	"jjqzplucky.site/sz-core/internal/models"
	medicalDeptModel "jjqzplucky.site/sz-core/internal/models/medical_dept"
	"jjqzplucky.site/sz-core/pkg/constants"
	"jjqzplucky.site/sz-core/pkg/errors"
	"jjqzplucky.site/sz-core/pkg/utils"
)

type MedicalDeptController struct {
}

func (d *MedicalDeptController) GetDeptTree(c *gin.Context) {

	depts, err := medical_dept_dao.SelectDeptAndSub()
	if err != nil {
		c.Error(err)
	}
	c.Set(constants.ResultData, depts)
}

func (d *MedicalDeptController) Create(c *gin.Context) {
	dto := medicalDeptModel.MedicalDeptDto{}
	if err := c.ShouldBindJSON(&dto); err != nil {
		c.Error(err)
		return
	}
	if dto.Recommended == nil {
		dto.Recommended = new(int8)
		*(dto.Recommended) = 0
	}
	model := medicalDeptModel.MedicalDept{}
	if err := utils.CopyStruct(&dto, &model); err != nil {
		c.Error(err)
		return
	}
	if err := medical_dept_dao.Create(model); err != nil {
		c.Error(err)
		return
	}
	c.Set(constants.ResultData, nil)

}

func (d *MedicalDeptController) Update(c *gin.Context) {
	dto := medicalDeptModel.MedicalDeptDto{}
	_ = c.ShouldBindJSON(&dto)
	if dto.Id <= 0 {
		c.Error(errors.ID_NOT_EXIST)
	}
	model := medicalDeptModel.MedicalDept{}
	if err := utils.CopyStruct(&dto, &model); err != nil {
		c.Error(err)
		return
	}
	if err := medical_dept_dao.Update(model); err != nil {
		c.Error(err)
		return
	}
	c.Set(constants.ResultData, nil)
}

func (d *MedicalDeptController) Delete(c *gin.Context) {
	id := c.Param("id")
	uid, err := strconv.ParseUint(id, 10, 64)
	if err != nil {
		c.Error(err)
		return
	}
	model := medicalDeptModel.MedicalDept{}
	model.Id = uid
	if err := medical_dept_dao.Delete(model); err != nil {
		c.Error(err)
		return
	}
	c.Set(constants.ResultData, nil)

}

func (d *MedicalDeptController) Page(c *gin.Context) {
	var param medicalDeptModel.PageQuery
	c.ShouldBindQuery(&param)
	result := medical_dept_dao.Page(param)
	c.Set(constants.ResultData, result)
}

func (d *MedicalDeptController) List(c *gin.Context) {
	var param models.PageParam
	_ = c.ShouldBindQuery(&param)
	c.Set(constants.ResultData, medical_dept_dao.PageWithSimple(param))
}
